<!--
  导入Codemirror组件
-->

<script>
import { codemirror } from 'vue-codemirror'
// 支持json以及json的相关提示
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'
// 支持json的折叠
import 'codemirror/addon/fold/indent-fold.js'
import 'codemirror/addon/fold/comment-fold'
import 'codemirror/addon/fold/foldcode.js'
import 'codemirror/addon/fold/foldgutter.js'
import 'codemirror/addon/fold/brace-fold.js'
import 'codemirror/addon/display/autorefresh'

export default {
  name: 'JsonCodeMirror',
  components: {
    codemirror
  },
  model: { // 定义model 实现v-model的双向绑定
    prop: 'code_from',
    event: 'codeChange'
  },
  props: {
    // eslint-disable-next-line vue/prop-name-casing
    code_from: {
      type: String,
      required: true,
      default: ''
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      'codeString': this.code_from,
      'options': {
        autoRefresh: true,
        line: true,
        theme: 'solarized', // 主题白色
        tabSize: 2, // 制表符的缩进位数
        foldGutter: true,
        gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers'],
        firstLineNumber: 1,
        autofocus: !this.disabled,
        readOnly: this.disabled || this.readOnly, // 只读
        smartIndent: true,
        lineNumbers: true, // 是否显示行数
        lineWrapping: true, // 自动换行
        viewportMargin: Infinity,
        showCursorWhenSelecting: true,
        highlightDifferences: true,
        mode: 'application/json' // 设置为 Json 模式
      }
    }
  },
  watch: {
    code_from(newVal) {
      this.codeString = newVal
    },
    codeString(newVal) {
      this.$emit('codeChange', newVal)
    },
    readOnly(newVal) {
      this.options.readOnly = newVal
    },
    disabled(newVal) {
      this.options.autofocus =!newVal
      this.options.readOnly = !newVal || this.readOnly
    }
  }
}
</script>

<template>
  <codemirror
    v-model="codeString"
    :options="options"
  />
</template>

<style scoped>
@import '~codemirror/lib/codemirror.css';
@import '~codemirror/theme/solarized.css';
@import '~codemirror/addon/lint/lint.css';
@import '~codemirror/addon/fold/foldgutter.css';

.cm-s-solarized.CodeMirror {
  box-shadow: none; /* 取消阴影  */
  /*border-left: 2px solid #4c566a;  自定义边框 */
  border: 2px solid gray; /* 自定义边框 */
}
</style>
